package com.lam.common.context;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

import com.lam.common.base.domain.LoginUser;

/**
 * 安全服务工具类
 * 
 * @author lam
 */
public class SecurityUtils {

	/**
	 * 获取当前登录用户名，当Principal为空时，返回null，不会从Redis中查询获取
	 * @return
	 */
	public static String getLoginUsername() {
		LoginUser loginUser = getLoginUser();
		if (loginUser == null) {
			return null;
		}
		return loginUser.getUsername();
	}

	/**
	 * 获取当前登录用户，当Principal为空时，返回null，不会从Redis中查询获取
	 * @return
	 */
	public static LoginUser getLoginUser() {
		Authentication auth = getAuthentication();
		if (auth == null) {
			return null;
		}
		Object principal = auth.getPrincipal();
		return principal instanceof LoginUser ? (LoginUser)principal : null;
	}
	
	/**
	 * 获取Authentication
	 */
	public static Authentication getAuthentication() {
		return SecurityContextHolder.getContext().getAuthentication();
	}

}
